package com.hm.shopping.auto.su;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hm.common.util.EncryptUtil.Base64;
import com.hm.shopping.auto.SystemEnvConfigProperties;

/**
 * @author shishun.wang
 * @date 2018年1月22日 上午10:52:07
 * @version 1.0
 * @describe
 */
public abstract class BaseController {

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	public static String DATA_PAGE_NOT_FOUND = "redirect:/404";

	SerializerFeature[] feature = { SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteMapNullValue };

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	protected void logout() {
		request.getSession().removeAttribute(R.Session.SUBSCRIBER_SESSION);
	}

	protected void putHtml(String data) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void putJson(Object obj) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			response.getWriter().print(JSONObject.toJSONString(obj));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void putJsonArray(Object obj) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			response.getWriter().print(JSONArray.toJSONString(obj));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void successful(Object obj) {
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("status", "successful");
		content.put("data", obj);
		putJson(content);
	}

	protected void failure(Object obj) {
		Map<String, Object> content = new HashMap<String, Object>();
		content.put("status", "failure");
		content.put("data", obj);
		putJson(content);
	}

	protected void commonAttribute(Model model, SystemEnvConfigProperties systemEnvConfigProperties) {
		model.addAttribute("errorMsg", request.getParameter("errorMsg"));
		model.addAttribute("successfulMsg", request.getParameter("successfulMsg"));
		model.addAttribute("copyrightStatement", new String(Base64.decode(systemEnvConfigProperties.getFooterCopyrightStatementPC().toCharArray())));// 版权信息
	}
}
